package cn.bluedot.tea.util;

import java.util.Map;

public class Page<E> {
	
	@SuppressWarnings("rawtypes")
	protected static final ThreadLocal<Page> LOCAL_PAGE = new ThreadLocal<Page>();

	private int pageNum; //页码，从1开始
	
	private int pageSize; //分页大小（一个分页导航的页码数）
	//总记录数
    private long total = -1;
    //总页数
    private int pages = -1;
    
        
    /**
     *	page存入当前线程
     * @param page
     */
    protected static void setLocalPage(Page<?> page) {
        LOCAL_PAGE.set(page);
    }

    /**
     * 	获取当前线程的Page
     * @return
     */
    @SuppressWarnings("unchecked")
	public static <E> Page<E> getLocalPage() {
        return LOCAL_PAGE.get();
    }

    /**
     * 	移除当前线程Page
     */
    public static void clearPage() {
        LOCAL_PAGE.remove();
    }

	public Page(int pageNum, int pageSize) {
		this.pageNum = pageNum > 0 ? pageNum : 1; //分页合理化
		this.pageSize = pageSize;
	}

	public static <E> Page<E> startPage(int pageNum, int pageSize) {
		
		Page<E> page = new Page<E>(pageNum, pageSize);
		
        setLocalPage(page);
        return page;
    }

	public int getPageNum() {
		return pageNum;
	}

	public void setPageNum(int pageNum) {
		this.pageNum = pageNum > 0 ? pageNum : 1;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public long getTotal() {
		return total;
	}

	public void setTotal(long total) {
		this.total = total;
		if (total == -1) {
            pages = 1;
            return;
        }
        if (pageSize > 0) {
            pages = (int) (total / pageSize + ((total % pageSize == 0) ? 0 : 1));
        } else {
            pages = 0;
        }
	}

	public int getPages() {
		return pages;
	}

	public void setPages(int pages) {
		this.pages = pages;
	}

	public Page<E> setLimit(Map<String, Object> param){
		param.put("startrow", (this.pageNum-1) * this.pageSize);
		param.put("pagesize", this.pageSize);
		return this;		
	}
	
}